<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in goodList" :key="index">
          <td><input type="checkbox" v-model="item.checked" /></td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="jian(index)">-</button>{{ item.num
            }}<button @click="add(index)">+</button>
          </td>
          <td>{{ item.price * item.num }}</td>
          <td><button @click="remove(index)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{ sum }}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
  methods: {
    jian(index) {
      if (this.goodList[index].num > 1) this.goodList[index].num--;
    },
    add(index) {
      this.goodList[index].num++;
    },
    remove(index) {
      this.goodList.splice(index, 1);
    },
  },
  computed: {
    isAll: {
      set(val) {
        this.goodList.forEach((item) => {
          item.checked = val;
        });
      },
      get() {
        return this.goodList.every((item) => item.checked === true);
      },
    },
    sum() {
      return (
        this.goodList.reduce((pve, item) => {
          if (item.checked === true) {
            return pve + item.price * item.num;
          } else {
            return pve + 0;
          }
        }, 0) || 0
      );
    },
  },
  // watch: {
  //   sum() {
  //     this.goodList.forEach((item) => {
  //       if (item.checked === true) {
  //         this.sum += item.price * item.num;
  //       }
  //     })
  //   },
  // },
};
</script>

<style></style>
